package com.sx.gongzhong.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.sx.gongzhong.MyApplication;
import com.sx.gongzhong.R;
import com.sx.gongzhong.activity.CheckInActivity;
import com.sx.gongzhong.activity.LoginActivity;
import com.sx.gongzhong.activity.MyAppealActivity;
import com.sx.gongzhong.activity.MyDefendRoadActivity;
import com.sx.gongzhong.activity.MyExposureActivity;
import com.sx.gongzhong.activity.MyHelpActivity;
import com.sx.gongzhong.activity.MyLettersActivity;
import com.sx.gongzhong.activity.SettingActivity;
import com.sx.gongzhong.activity.UserInfoActivity;
import com.sx.gongzhong.model.IntegralBean;
import com.sx.gongzhong.model.MsgEvent;
import com.sx.gongzhong.model.UserInfoBean;
import com.sx.gongzhong.net.MyRxBus;
import com.sx.gongzhong.net.ServiceFactory;
import com.sx.gongzhong.pest.IntegralPest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.view.IntegralView;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by XZY on 2017/12/28.
 * 我的
 */
public class MyFragment extends LazyFragment implements IntegralView {

    @BindView(R.id.tv_checkin)
    TextView tvCheckin;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tvname)
    TextView tvname;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.tv_myIntegral)
    TextView tvMyIntegral;
    @BindView(R.id.tv_myGoldcoins)
    TextView tvMyGoldcoins;

    private Disposable disposable;
    private boolean isPrepared = false;
    private String integral = "0";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        ButterKnife.bind(this, view);
        isPrepared = true;
        initView();
        initRx();
        return view;
    }

    private void initRx() {
        disposable = MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent msgEvent) throws Exception {
                        if ("MyFragment".equals(msgEvent.getRequest())) {
                            if (msgEvent.getType() == 1) {//修改用户信息
                                initView();
                            }else if (msgEvent.getType() == 2){//登录
                                initView();
                                new IntegralPest(MyFragment.this).getMyIntegral();
                            }else if (msgEvent.getType() == 3){//签到成功
                                tvCheckin.setText("已签到");
                                tvCheckin.setBackgroundResource(R.drawable.shape_white_coners_60c8ff_solid);
                            }
                        }
                    }
                });
    }

    private void initView() {
        UserInfoBean userBean = MyApplication.instance.userBean;
        if (userBean != null && !BaseUtil.isEmpty(userBean.sid)) {
            setInfo(userBean);
        } else {
            tvLevel.setText("LV.0");
            tvMyIntegral.setText("0");
            tvMyGoldcoins.setText("0");
            tvname.setText("登录/注册");
            tvCheckin.setText("签到");
            tvCheckin.setBackgroundResource(R.drawable.shape_white_coners_style_solid);
            ivHead.setImageResource(R.mipmap.img_head_default);
        }
    }

    private void setInfo(UserInfoBean userBean) {
        tvname.setText(userBean.name);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//获取当前时间
        Date date = new Date(System.currentTimeMillis());
        if (userBean.lastCheckInDate.equals(simpleDateFormat.format(date))){
            tvCheckin.setText("已签到");
            tvCheckin.setBackgroundResource(R.drawable.shape_white_coners_60c8ff_solid);
        }else {
            tvCheckin.setText("签到");
            tvCheckin.setBackgroundResource(R.drawable.shape_white_coners_style_solid);
        }
        if (userBean.header != null && !BaseUtil.isEmpty(userBean.header.getPath())) {
            RequestOptions options = new RequestOptions().centerCrop()
                    .placeholder(R.mipmap.img_head_default)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .circleCrop()
                    .error(R.mipmap.img_head_default);
            Glide.with(this)
                    .load(ServiceFactory.getUrl(userBean.header.getPath()))
                    .apply(options)
                    .into(ivHead);
        }else {
            ivHead.setImageResource(R.mipmap.img_head_default);
        }
    }

    @OnClick({R.id.iv_head, R.id.tv_checkin, R.id.rl_setting, R.id.rl_my_exposure, R.id.rl_my_appeal,
            R.id.rl_my_help, R.id.rl_my_letter, R.id.rl_my_dangrouse})
    public void onClick(View view) {
        if (view.getId() == R.id.rl_setting) {
            startActivity(new Intent(getActivity(), SettingActivity.class));
            return;
        }
        if (MyApplication.instance.userBean == null || BaseUtil.isEmpty(MyApplication.instance.userBean.sid)) {
            Intent intent = new Intent(MyApplication.context, LoginActivity.class);
            startActivity(intent);
            return;
        }
        switch (view.getId()) {
            case R.id.iv_head:
                startActivity(new Intent(getActivity(), UserInfoActivity.class));
                break;
            case R.id.tv_checkin:
                startActivity(new Intent(getActivity(), CheckInActivity.class).putExtra("integral",integral));
                break;
            case R.id.rl_my_exposure://我的爆料
                startActivity(new Intent(getActivity(), MyExposureActivity.class));
                break;
            case R.id.rl_my_appeal://我的诉求
                startActivity(new Intent(getActivity(), MyAppealActivity.class));
                break;
            case R.id.rl_my_help://我的问问（互帮互助）
                startActivity(new Intent(getActivity(), MyHelpActivity.class));
                break;
            case R.id.rl_my_letter://我的信访举报
                startActivity(new Intent(getActivity(), MyLettersActivity.class));
                break;
            case R.id.rl_my_dangrouse://我的隐患上报
                startActivity(new Intent(getActivity(), MyDefendRoadActivity.class));
                break;
        }
    }

    @Override
    protected void lazyLoad() {
        if (isPrepared && isVisible) {
            isPrepared = false;
            new IntegralPest(this).getMyIntegral();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        if (disposable != null) {
            disposable.dispose();
        }
        super.onDestroy();
    }

    @Override
    public void showError(String message) {

    }

    @Override
    public void success(IntegralBean integralBean) {
        integral = integralBean.integral;
        tvLevel.setText("LV."+integralBean.level);
        tvMyIntegral.setText(integralBean.integral);
        tvMyGoldcoins.setText(integralBean.gold);
    }
}
